﻿using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 等同于集成了ContentSize Filtter的VerticalLayoutGroup
/// </summary>
public class AutoSizeVerticalLayoutGroup : HorizontalOrVerticalLayoutGroup
{
    [Header("Auto Size Settings")]
    [SerializeField] private bool m_AutoFitHeight = true;
    [SerializeField] private bool m_AutoFitWidth = false;

    public bool autoFitHeight
    {
        get { return m_AutoFitHeight; }
        set { SetProperty(ref m_AutoFitHeight, value); }
    }

    public bool autoFitWidth
    {
        get { return m_AutoFitWidth; }
        set { SetProperty(ref m_AutoFitWidth, value); }
    }

    public override void CalculateLayoutInputHorizontal()
    {
        base.CalculateLayoutInputHorizontal();
        CalcAlongAxis(0, true);

        if (m_AutoFitWidth || m_AutoFitHeight)
        {
            UpdateLayoutSize();
        }
    }

    public override void CalculateLayoutInputVertical()
    {
        CalcAlongAxis(1, true);
        if (m_AutoFitWidth || m_AutoFitHeight)
        {
            UpdateLayoutSize();
        }
    }

    public override void SetLayoutHorizontal()
    {
        SetChildrenAlongAxis(0, true);
    }

    public override void SetLayoutVertical()
    {
        SetChildrenAlongAxis(1, true);

        if (m_AutoFitWidth || m_AutoFitHeight)
        {
            UpdateLayoutSize();
        }
    }

    private void UpdateLayoutSize()
    {
        if (rectTransform == null) return;

        Vector2 currentSize = rectTransform.sizeDelta;

        // 计算高度
        if (m_AutoFitHeight)
        {
            float totalHeight = CalculateTotalHeight();
            currentSize.y = totalHeight;
        }

        // 计算宽度
        if (m_AutoFitWidth)
        {
            float totalWidth = CalculateTotalWidth();
            currentSize.x = totalWidth;
        }

        rectTransform.sizeDelta = currentSize;
    }

    private float CalculateTotalHeight()
    {
        float totalHeight = padding.top + padding.bottom;
        int validChildCount = 0;

        for (int i = 0; i < rectChildren.Count; i++)
        {
            RectTransform child = rectChildren[i];
            if (child == null || !child.gameObject.activeInHierarchy)
                continue;

            float childHeight = child.sizeDelta.y;
            totalHeight += childHeight;
            validChildCount++;
        }

        // 添加间距
        if (validChildCount > 1)
            totalHeight += spacing * (validChildCount - 1);

        return totalHeight;
    }

    private float CalculateTotalWidth()
    {
        float maxWidth = 0f;

        for (int i = 0; i < rectChildren.Count; i++)
        {
            RectTransform child = rectChildren[i];
            if (child == null || !child.gameObject.activeInHierarchy)
                continue;

            float childWidth = child.sizeDelta.x;
            maxWidth = Mathf.Max(maxWidth, childWidth);
        }

        return maxWidth + padding.left + padding.right;
    }
}